package com.vpx.server.framework.exception;

import com.vpx.server.framework.base.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author denglw
 * @title: command
 * @module TODO
 * @description: TODO
 * @date 2022/7/23 22:45
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.vpx.server.controller")
public class ExceptionAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultMsg handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder msgBuilder = new StringBuilder();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            msgBuilder.append(fieldError.getField() + "->" + fieldError.getDefaultMessage() + ";");
        });
        return ResultMsg.fail(msgBuilder.toString());
    }

    @ExceptionHandler(BizException.class)
    public ResultMsg handleBizException(BizException e) {
        return ResultMsg.fail(e.getMessage());
    }
}
